package com.chenhy.service;

import com.chenhy.mapper.BillMapper;
import com.chenhy.pojo.Bill;
import com.chenhy.pojo.Provider;
import com.chenhy.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.List;

@Service
public class BillServiceImpl implements BillService {

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private ProviderService providerService;

    @Override
    @Cacheable(value = "bill", key = "'billList'")
    public List<Bill> queryAllBill() {
        return billMapper.queryAllBill();
    }

    @Override
    public List<Bill> fuzzyBillQuery(String condition) {
        return billMapper.fuzzyBillQuery(condition);
    }

    @Override
    @CacheEvict(value = "bill", key = "'billList'")
    public int addBill(Bill bill) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        bill.setCreatedBy(loginUser.getId());
        bill.setModifyBy(loginUser.getId());
        return billMapper.addBill(bill);
    }

    @Override
    @Transactional
    @Cacheable(value = "bill", key = "#id")
    public Bill queryBillById(int id) {
        Bill bill = billMapper.queryBillById(id);
        Provider provider = providerService.queryProviderById(bill.getProviderId());
        bill.setProviderName(provider.getProName());
        return bill;
    }

    @Override
    @Caching(evict = {@CacheEvict(value = "bill", key = "#bill.id"),
            @CacheEvict(value = "bill", key = "'billList'")
    })
    public int updateBill(Bill bill) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        bill.setModifyBy(loginUser.getId());
        return billMapper.updateBill(bill);
    }

    @Override
    @Caching(evict = {@CacheEvict(value = "bill", key = "#bill.id"),
            @CacheEvict(value = "bill", key = "'billList'")
    })
    public int deleteBill(int id) {
        return billMapper.deleteBill(id);
    }
}
